package com.whfp.coky.utils

import android.content.Context
import com.google.gson.*
import com.google.gson.reflect.TypeToken
import com.tencent.bugly.crashreport.CrashReport
import org.json.JSONArray
import org.json.JSONException
import java.io.*
import java.lang.reflect.Type

/**
 *
 *
 * created by coky on 2022/3/21
 */
class GsonUtils : JsonSerializer<String>, JsonDeserializer<String>{
   companion object{

       /**
        * 解析普通json
        *
        * @param json  要解析的json
        * @param clazz 对应的实体类
        * @param <T>   泛型
        * @return
       </T> */
       fun <T> parseJSON(json: String?, clazz: Class<T>?): T {
           val gb = GsonBuilder()
           gb.registerTypeAdapter(String::class.java, GsonUtils())
           val gson = gb.create()
           return gson.fromJson(json, clazz)
       }

       /**
        * 解析泛型json
        *
        * @param json 要解析的json
        * @param type 要解析json的泛型类型
        * @param <T>  泛型
        * @return
       </T> */
       fun <T> parseJSON(json: String?, type: Type?): T {
           val gb = GsonBuilder()
           gb.registerTypeAdapter(String::class.java, GsonUtils())
           val gson = gb.create()
           return gson.fromJson(json, type)
       }

       /**
        * 解析对象型的数组的json
        *
        * @param json  要解析的json
        * @param clazz 对应的实体类
        * @param <T>   泛型
        * @return
       </T> */
       fun <T> jsonToArrayList(json: String?, clazz: Class<T>?): MutableList<T> {
           val gb = GsonBuilder()
           gb.registerTypeAdapter(String::class.java, GsonUtils())
           val type = object : TypeToken<MutableList<JsonObject?>?>() {}.type
           val jsonObjects = gb.create().fromJson<MutableList<JsonObject>>(json, type)
           val arrayList = mutableListOf<T>()
           for (jsonObject in jsonObjects) {
               arrayList.add(Gson().fromJson(jsonObject, clazz))
           }
           return arrayList
       }

       /**
        * 得到assets文件夹中json文件中的内容
        *
        * @param context
        * @param fileName
        * @return
        */
       fun getJsonFromAssets(context: Context, fileName: String): String {
           val stringBuilder = StringBuilder()
           //获得assets资源管理器
           val assetManager = context.assets
           //使用IO流读取json文件内容
           try {
               val bufferedReader = BufferedReader(
                   InputStreamReader(
                       assetManager.open(fileName), "utf-8"
                   )
               )
               var line: String
               while (bufferedReader.readLine().also { line = it } != null) {
                   stringBuilder.append(line.trim())
               }
           } catch (e: IOException) {
               e.printStackTrace()
           }
           LogUtil.e("stringBuilder.toString()${stringBuilder.toString()}")
           return stringBuilder.toString()
       }


       fun readAssets(context: Context,fileName:String):String{

           val input = context.assets.open(fileName)
           val inputstreamreader = BufferedReader(InputStreamReader(input))
           try
           {
               LogUtil.e("获取的assets文本内容----${inputstreamreader.readLines().toString()}")
               return inputstreamreader.readLines().toString()
           }
           catch (e: IOException)
           {
               e.printStackTrace()
           }
           finally
           {
               inputstreamreader.close()
           }
           return "读取失败,请检查文件名称及文件是否存在!"
       }

       fun readAssetsJson(context: Context,fileName:String):String{
           return context.resources.assets.open(fileName).let {
               it.buffered().reader().use { reader ->
                   reader.readText()
               }
           }
       }

       /**
        * 获取资产目录下面文件的字符串
        */
       private fun readAssetsJson2(context: Context,fileName:String): JSONArray? {
           try {
               val inputStream: InputStream =
                   context.resources.assets.open(fileName)
               val outStream = ByteArrayOutputStream()
               val buffer = ByteArray(512)
               var length: Int
               while (inputStream.read(buffer).also { length = it } != -1) {
                   outStream.write(buffer, 0, length)
               }
               outStream.close()
               inputStream.close()
               return JSONArray(outStream.toString())
           } catch (e: IOException) {
               CrashReport.postCatchedException(e)
           } catch (e: JSONException) {
               CrashReport.postCatchedException(e)
           }
           return null
       }



   }

    override fun serialize(
        src: String?,
        typeOfSrc: Type?,
        context: JsonSerializationContext?
    ): JsonElement {
        return if (src == null) {
            JsonPrimitive("")
        } else {
            JsonPrimitive(src.toString())
        }
    }

    override fun deserialize(
        json: JsonElement,
        typeOfT: Type?,
        context: JsonDeserializationContext?
    ): String {
        return json.getAsJsonPrimitive().getAsString()
    }

}